package com.ea.admin.schedule;


import com.ea.admin.service.SseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

import static com.ea.admin.service.impl.SseServiceImpl.sseDataMap;

@Slf4j
@Component
@EnableScheduling
public class SendMessageTask {
    @Resource
    private SseService sseService;

    /**
     * 定时执行 秒 分 时 日 月 周
     */
    // 间隔10s执行
    @Scheduled(cron = "0/10 * * * * ?")
    public void sendMessageTask() {
        sseDataMap.forEach((clientId, sseData) -> {
            Long userId = sseData.getUserId();
            SseEmitter sseEmitter = sseData.getSseEmitter();
            // 检查连接是否正常
            sseEmitter.onTimeout(() -> sseService.closeSseConnect(clientId));
            // 发送次数 + 1 发送次数达到 30，说明已经发送了 30 * 10 = 300s 也就是 5分钟
            int count = sseData.incrementSendCount();
            if (count >= 30) {
                log.info("用户{} 连接已发送30次，关闭连接", userId);
                sseService.closeSseConnect(clientId);
                return;
            }
            sseService.sendMessage(userId, clientId, sseEmitter);
        });
    }
}

